package com.online.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;

/**
 * JSON转换工具类
 * 
 * @author trunks
 * @version $Id: JsonUtils.java, v 0.1 2012-3-7 下午04:49:24 trunks Exp $
 */
public class JsonUtils {

    private String         dateFormate = "yyyy-MM-dd HH:mm:ss";
    private JSONSerializer jsonSerializer;

    public JsonUtils(String... includes) {
        jsonSerializer = new JSONSerializer();
        jsonSerializer.include(includes);
        jsonSerializer.exclude("*.class");
        /*
        List<String> excludes = new ArrayList<String>(exclude.length + 1);
        for (String e : exclude) {
            excludes.add(e);
        }
        excludes.add("*.class");
        jsonSerializer.exclude(excludes.toArray(new String[excludes.size()]));
        */

        jsonSerializer.transform(new DateTransformer(getDateFormate()), Date.class);
    }

    /**
     * 初始化JSONSerializer，默认过滤掉class，并将所有的java.util.Date转换成yyyy-MM-dd HH:mm:ss格式。
     * 
     * @param includes 包含的属性
     */
    public static JsonUtils buildJSONSerializaer(String... includes) {
        return new JsonUtils(includes);
    }

    /**
     * 转换JSON对象，调用前先调用buildJSONSerializaer
     */
    public String writeObjectJson(Object obj) {
        return jsonSerializer.serialize(obj);
    }

    /**
     * 转换JSON对象为Ext表单提交成功的方式，调用前先调用buildJSONSerializaer<br />
     * 
     * 对于com.hosane.cms.dao.PageInfo对象，直接调用writeObjectJson即可<br /><br />
     * ex.{"success":"false","errors":{"name":"名称已存在"}}
     * 
     * @param obj 错误信息，若用map，Key若为表单项的name，则会自动在对应表单项显示错误信息
     * @param success true为result，false为errors
     */
    public String writeFormObjectJson(Object obj, boolean success) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", success);
        if (success) {
            map.put("result", obj);
        } else {
            map.put("errors", obj);
        }
        return jsonSerializer.deepSerialize(map);
    }
    
    /**
     * 转换分页数据
     * 
     * @param list 结果集
     * @param total 记录数
     */
    public String writePageObjectJson(Object list, Object total) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("list", list);
        map.put("totalCount", total);
        return jsonSerializer.deepSerialize(map);
    }

    public String getDateFormate() {
        return dateFormate;
    }

    public void setDateFormate(String dateFormate) {
        this.dateFormate = dateFormate;
    }

}
